package org.argus.management.data.service;

import lombok.extern.slf4j.Slf4j;
import org.argus.common.mybatis.utils.DBUtils;
import org.argus.common.redis.service.RedisService;
import org.argus.common.web.core.data.DataValueCacheUtils;
import org.argus.common.web.core.data.model.BuildCacheReq;
import org.argus.common.web.core.data.model.CacheFieldReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author 刘文/Cliff Liu
 * @Date 2024/7/30
 */
@Service
@Slf4j
public class DataCacheService {

    @Autowired
    private DBUtils dbUtils;

    @Autowired
    private RedisService redisService;

    @Value("${argus.data.cache.timeSeconds: 300}")
    private long cacheTimeSeconds;

    public Map<String, String> buildCache(BuildCacheReq req) {
        Map<String, String> result = new HashMap<>();
        for (CacheFieldReq cacheFieldReq : req.getCacheFieldReqs()) {
            String sql = "select " + cacheFieldReq.getValueColumn() + ", " + cacheFieldReq.getKeyColumn() + " from "
                + cacheFieldReq.getSourceTable() + " where " + cacheFieldReq.getKeyColumn() + " in (";
            sql += cacheFieldReq.getKeys().stream().map(key -> "'" + key + "'").collect(Collectors.joining(","));
            sql += ")";
            List<Map<String, Object>> rows = dbUtils.executeQuerySql(sql);
            log.info("Build cache using sql: {}", sql);
            for (Map<String, Object> row : rows) {
                String key =
                    DataValueCacheUtils.buildDataCacheKey(cacheFieldReq.getSourceTable(), cacheFieldReq.getKeyColumn(),
                        row.get(cacheFieldReq.getKeyColumn()).toString(), cacheFieldReq.getValueColumn());
                result.put(key, row.get(cacheFieldReq.getValueColumn()).toString());
                redisService.setCacheObject(key, row.get(cacheFieldReq.getValueColumn()).toString(), cacheTimeSeconds,
                    TimeUnit.SECONDS);
            }
        }
        return result;
    }
}
